### "Allegiance, Ability, and Achievement in the American Civil War:
### Commander Traits and Battlefield Military Effectiveness"

### By Jeffrey B. Arnold, J. Tyson Chatagnier, and Gary E. Hollibaugh, Jr.

##### BATTLE UPDATING CODE.
##### CAN BE USED TO UPDATE BATTLE DATA IF NEW SOURCES ARE USED WITHOUT DISRUPTING WORKFLOW.
##### DO NOT CALL DIRECTLY.

# Set file targets.
FILE_OLDBATTLES <- file.path(DIR_DATA, "ACH-BattleCommanders.dta")
FILE_NEWBATTLES <- file.path(DIR_DATA, "ACH-BattlesImputed.rds")
FILE_TARGET <- file.path(DIR_DATA, "ACH-NewBattles.rds")


# Load "blank" battle-commander data and (imputed) battle data.
oldbattles <- read.dta(FILE_OLDBATTLES)
newbattles <- data.frame(readRDS(FILE_NEWBATTLES))

# Change column names for later use.
colnames(newbattles)[colnames(newbattles) == "cwsac_id"] <- "battle"
colnames(newbattles)[colnames(newbattles) == "result"] <- "results"

# Merge everything together.
merged_battles <- merge(oldbattles, newbattles, by = "battle")

# Recode a couple of things.
merged_battles$surrender_side <- "None"
merged_battles$surrender_side[grep("Confederate", merged_battles$surrender)] <- "Confederate"
merged_battles$surrender_side[grep("Union", merged_battles$surrender)] <- "Union"
merged_battles$surrender_side <- factor(merged_battles$surrender_side)
merged_battles$start_date1 <- as.numeric(as.Date(merged_battles$start_date, origin = "1970-01-01"))
merged_battles$end_date <- merged_battles$start_date + merged_battles$duration
merged_battles$end_date1 <- as.numeric(as.Date(merged_battles$end_date, origin = "1970-01-01"))

# Rename some columns for backwards compatibility
colnames(merged_battles)[6:9] <- c("US_casualties", "US_strength",
                                   "CS_casualties", "CS_strength")

# Save to a file.
saveRDS(merged_battles, file = FILE_TARGET)
